package fragmentson;

import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.wq.cycling.R;

import java.util.ArrayList;
import java.util.List;

import fragmentson.backhandle.BackHandledFragment;
import util.adapter.SearchAdapter;

/**
 * 选择报失地址 地图页
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class ReportLoss_E extends BackHandledFragment implements AMap.OnMyLocationChangeListener,InputtipsListener {

	private View rootView;
	private TextureMapView mapView;
	private AMap aMap;
	private GeocodeSearch geocoderSearch;
	private ListView lv_searchlist;
	private SearchAdapter adapter;
	private EditText et_search;
	private List<Tip> mlist = new ArrayList<>();
	private String address = "";
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_reportloss_e, null);
		/*初始化地图和amap对象*/
		mapView = (TextureMapView) rootView.findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		if (aMap == null) {
			aMap = mapView.getMap();
		}
		initView();
		initMapView();
		return rootView;
	}

	private void initView() {
		// TODO Auto-generated method stub
		lv_searchlist = ((ListView) rootView.findViewById(R.id.lv_searchlist));
		et_search = ((EditText) rootView.findViewById(R.id.et_search));
		et_search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence cs, int start, int before, int count) {
				// TODO Auto-generated method stub
				if(lv_searchlist.getVisibility()==View.GONE) {
					lv_searchlist.setVisibility(View.VISIBLE);
				}
				if(count==0){
					lv_searchlist.setVisibility(View.GONE);
				}
				InputtipsQuery inputquery = new InputtipsQuery(et_search.getText().toString(), "");
				inputquery.setCityLimit(false);//不限制在当前城市
				Inputtips inputTips = new Inputtips(getActivity(), inputquery);
				inputTips.setInputtipsListener(ReportLoss_E.this);
				inputTips.requestInputtipsAsyn();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}
		});

		adapter = new SearchAdapter(getActivity(), mlist);
		lv_searchlist.setAdapter(adapter);
		lv_searchlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				getAddress(mlist.get(position).getPoint().getLatitude(), mlist.get(position).getPoint().getLongitude());
				lv_searchlist.setVisibility(View.GONE);
			}
		});

	}

	private void initMapView(){
		//隐藏缩放组件
		aMap.getUiSettings().setZoomControlsEnabled(false);
		//logo位置
		aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);
		//加载定位maker
		//initMarkers()
		// 初始化反地理编码;
		initGeocoder();
		aMap.setOnMyLocationChangeListener(this);
		locationBlue();
	}

	public void locationBlue(){
		MyLocationStyle myLocationStyle;
		myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
		myLocationStyle.strokeColor(Color.argb(0,0,0,0));
		myLocationStyle.radiusFillColor(Color.argb(0,0,0,0));//设置定位蓝点精度圆圈的填充颜色的方法。
		myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.icon_transparency));// 设置小蓝点的图标
		myLocationStyle.anchor(0.5f,0.8f);
		//myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//指定为一次并拉到中心
		myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//指定为一次并拉到中心
		myLocationStyle.interval(10000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
		aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
		aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
	}

	public static ReportLoss_E newInstance(CallBackListener call) {
		ReportLoss_E fragment = new ReportLoss_E();
		mcall = call;
		return fragment;
	}


	@Override
	public boolean onBackPressed() {
		mcall.listener(address);
		return false;
	}

	/**
	 * 初始化逆地理编码组件
	 */
	private void initGeocoder(){
		geocoderSearch = new GeocodeSearch(getActivity());
		geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
			@Override
			public void onRegeocodeSearched(RegeocodeResult result, int rCode) {

				if (rCode == AMapException.CODE_AMAP_SUCCESS) {
					if (result != null && result.getRegeocodeAddress() != null
							&& result.getRegeocodeAddress().getFormatAddress() != null) {
						address = result.getRegeocodeAddress().getFormatAddress();
					} else {
						Toast.makeText(getActivity(),"无数据",Toast.LENGTH_LONG).show();
					}
				} else {
					Toast.makeText(getActivity(),rCode,Toast.LENGTH_LONG).show();
				}
			}

			@Override
			public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

			}
		});
	}

	@Override
	public void onMyLocationChange(Location location) {
		if(location != null) {
			//如果想改变地图中心点
			getAddress(location.getLatitude(),location.getLongitude());
		}
	}

	public void getAddress(double lat,double lng){
		aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(lat, lng),16,0,0)));
		LatLonPoint latLonPoint = new LatLonPoint(lat,lng);
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
		geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
	}


	/**
	 * 方法必须重写
	 */
	@Override
	public void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onPause() {
		super.onPause();
		mapView.onPause();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	@Override
	public void onGetInputtips(List<Tip> list, int i) {
		if(list!=null) {
			mlist.clear();
			for(Tip tip:list){
				if(tip.getPoiID()!=null&&tip.getPoint()!=null){
					mlist.add(tip);
				}
			}
			adapter.notifyDataSetChanged();
		}
	}

	public static interface CallBackListener{
		void listener(String item);
	}
	private static CallBackListener mcall;
}
